package com.cbh.binlog.link.factory;

import com.cbh.binlog.core.SchemaParser;
import com.cbh.binlog.link.BinaryLogEventListener;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * Binlog事件监听器 责任链工厂
 *
 * @author ChenBiHui
 * @date 2025/1/16
 */
@Slf4j
public class BinaryLogEventListenerFactory {

    private static BinaryLogEventListener START;

    public BinaryLogEventListenerFactory(List<BinaryLogEventListener> impls) {
        BinaryLogEventListener move = null;
        List<String> modify = new ArrayList<>();
        for (int i = 0; i < impls.size(); i++) {
            if (i == 0) {
                move = impls.get(i);
                modify.add(SchemaParser.compose(move.schema(), move.table()));
            } else {
                BinaryLogEventListener callback = impls.get(i);
                callback.setNext(move);
                move = callback;
                if (modify.contains(SchemaParser.compose(move.schema(), move.table()))) {
                    throw new IllegalArgumentException("There are too many callback in your binary-log-callback impl with [" + SchemaParser.compose(move.schema(), move.table()) + "]");
                }
                modify.add(SchemaParser.compose(move.schema(), move.table()));
            }
        }
        START = move;
    }

    public static BinaryLogEventListener start() {
        return START;
    }
}
